# users/views.py
from django.forms import model_to_dict
from django.http import JsonResponse
from rest_framework.permissions import IsAuthenticated
from rest_framework.request import Request
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from django.contrib.auth.hashers import make_password
from rest_framework_simplejwt.tokens import RefreshToken

from utils.JwtUtil import create_token, verify_token
from utils.ResponseResult import ResponseResult
from .models import User
from django.core.exceptions import ObjectDoesNotExist

from .serializers import UserSerializer
from .utils import hash_password


class RegisterView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')
        confirm_password = request.data.get('confirm_password')

        if password != confirm_password:
            return JsonResponse({"error": "两次密码不一致"}, status=status.HTTP_400_BAD_REQUEST)

        if User.objects.filter(username=username).exists():
            return JsonResponse({"error": "用户名已存在"}, status=status.HTTP_400_BAD_REQUEST)

        hashed_password = hash_password(password)

        User.objects.create(
            username=username,
            password=hashed_password,
            # 其他字段...
        )

        return JsonResponse({"message": "注册成功","code":200}, status=status.HTTP_200_OK)


class LoginView(APIView):
    def post(self, request):
        username = request.data.get('username')
        password = request.data.get('password')

        if not username or not password:
            return JsonResponse({"error": "用户名和密码不能为空"}, status=status.HTTP_400_BAD_REQUEST)

        try:
            user = User.objects.get(username=username)
        except ObjectDoesNotExist:
            return JsonResponse({"error": "账号不存在"}, status=status.HTTP_400_BAD_REQUEST)

        # 对传入的明文密码进行加密
        hashed_input = hash_password(password)

        # 与数据库中存储的密码比对
        if hashed_input != user.password:
            return JsonResponse({"error": "密码错误"}, status=status.HTTP_400_BAD_REQUEST)

        # 密码正确，生成 Token 或直接返回用户信息（这里你可以接入 JWT）
        refresh = create_token(model_to_dict(user))
        return JsonResponse({
            'code':200,
            'message': '登录成功',
            'data': str(refresh)
        }, status=status.HTTP_200_OK)


class GetUserInfoView(APIView):
    def get(self, request: Request) -> JsonResponse:
        # 1. 获取 Authorization Header
        auth_header = request.headers.get('Authorization')

        if not auth_header:
            return JsonResponse({"message": "未提供 Token", "code":401})

        try:
            token = auth_header.split(" ", 1)[1].strip()

            # 3. 使用你的工具类验证 Token
            claims = verify_token(token)
            if not claims:
                return JsonResponse({"message": "无效或过期的 Token", "code": 401})

            # 4. 从 claims 中取出用户 ID 并查询用户
            user_id = claims.get("user_id")
            if not user_id:
                return JsonResponse({"message": "Token 中缺少用户信息", "code": 401})

            try:
                user = User.objects.get(user_id=user_id)
            except User.DoesNotExist:
                return JsonResponse({"message": "用户不存在", "code": 404})

            # 5. 序列化用户信息并返回
            serializer = UserSerializer(user)
            return JsonResponse({"code":200,"data":serializer.data})

        except Exception as e:
            return ResponseResult.error(message=f"服务器错误: {str(e)}", code=500)
